import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import { cloumsAdd, cloumsModify } from '@/services/colums';
import React, { useState, useRef } from 'react';
import { message, Switch } from 'antd';
import { SetPageOption } from './readOnly.config';
import CalculatorPage from './CalculatorPage';

export type UpdatePageProps = {
  pageType?: number;
  pageData?: CLOUMS.CLOUMSListItem;
  show: boolean;
  showFn: any;
  reload: any;
  indicatorData: CLOUMS.CLOUMSListItem[] | undefined;
};

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: CLOUMS.CLOUMSAdd) => {
  const hide = message.loading('正在添加...');
  try {
    await cloumsAdd({ ...fields });
    message.success('添加成功！');
    return true;
  } catch (error) {
    message.error('修改失败！');
    return false;
  } finally {
    hide();
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 * @param fields
 */
const handleUpdate = async (fields: CLOUMS.CLOUMSModify) => {
  const hide = message.loading('正在修改...');
  try {
    await cloumsModify({
      name: fields.name,
      code: fields.code,
      type: fields.type,
      computed: fields.computed,
    });
    message.success('修改成功！');
    return true;
  } catch (error) {
    message.error(error);
    return false;
  } finally {
    hide();
  }
};

/* 指标公式生成 */
const computedStringFn = (data: CLOUMS.Computed[] | undefined) => {
  let str = '';
  if (data && data.length > 0) {
    data.forEach((el, index) => {
      /* 为了好看 进行 处理 */
      if (index === data.length - 1) {
        str += el.name;
      } else {
        str += el.name + ' ';
      }
    });
    return str;
  } else {
    str = '';
  }
  return str;
};

const CloumsPage: React.FC<UpdatePageProps> = (props) => {
  // 计算器的 显示 隐藏
  const [calculatorShow, setCalculatorShow] = useState<boolean>(false);

  /* 指标数据 */
  const indicatorData = props.indicatorData;
  console.log(86, indicatorData);

  /* 页面数据 */
  const pageData = props.pageData;

  /**
   * 当前数据类型
   * 基础: 1  必要: 2  自定义: 3
   **/
  const paramsType = pageData?.type;

  /**
   * 当前页面类型
   * 新增: 1  修改: 2  详情: 3
   **/
  const pageType = props.pageType;

  /* 指标公式数据 */
  const [computedData, setComputedData] = useState(pageData?.computed);

  const [computedString, setComputedString] = useState(computedStringFn(computedData));

  // 生成页面的配置参数
  const pageOption = SetPageOption(pageType, paramsType);

  const formRef = useRef<ProFormInstance>();

  const restModalFormData = (arr: any) => {
    formRef.current?.setFieldsValue({
      computed: computedStringFn(arr),
    });
    setComputedData(arr);
    setComputedString(computedStringFn(arr));
  };
  return (
    <ModalForm
      title={pageOption.title}
      width="500px"
      visible={props.show}
      onVisibleChange={props.showFn}
      layout="horizontal"
      formRef={formRef}
      onFinish={async (value) => {
        let result = null;
        value.computed = computedData;
        if (pageType === 1) {
          result = await handleAdd(value as CLOUMS.CLOUMSAdd);
        } else {
          result = await handleUpdate(value as CLOUMS.CLOUMSModify);
        }
        if (result) {
          props.reload?.reload();
          setCalculatorShow(false);
          props.showFn(false);
        }
      }}
      /* 控制 footer 提交按钮是否展示  */
      submitter={{
        submitButtonProps: {
          style: {
            display: pageType == 3 ? 'none' : 'block',
          },
        },
      }}
    >
      <ProFormText
        label="指标名称:"
        name="name"
        width="md"
        initialValue={pageData?.name}
        placeholder="请选择指标名称"
        readonly={pageOption.readOnly}
        rules={[
          {
            required: true,
            message: '指标编码为必填项',
          },
        ]}
      />
      <ProFormText
        label="指标编码:"
        name="code"
        width="md"
        initialValue={pageData?.code}
        placeholder="请输入指标编码"
        readonly={!pageOption.codeWrite}
        rules={[
          {
            required: true,
            message: '指标类型为必选项',
          },
        ]}
      />
      <ProFormSelect
        name="type"
        label="指标类型:"
        width="md"
        readonly
        placeholder="请选择指标类型"
        disabled
        initialValue={pageData?.type ? pageData?.type : '3'}
        request={async () => [
          { label: '基础指标', value: '1' },
          { label: '必要指标', value: '2' },
          { label: '自定义指标', value: '3' },
        ]}
        rules={[
          {
            required: true,
            message: '指标公式为必填项',
          },
        ]}
      />
      <span className="ant-col ant-form-item-label">
        <label title="编辑指标:">编辑指标</label>
      </span>
      <Switch
        checked={calculatorShow}
        checkedChildren="开"
        unCheckedChildren="关"
        disabled={pageOption.computedWrite}
        onChange={setCalculatorShow}
      />
      <ProFormText
        label="公式:"
        name="computed"
        width="md"
        placeholder="请输入指标公式"
        readonly
        initialValue={computedString}
        rules={[
          {
            required: pageOption.expRequire,
            message: '指标公式为必填项',
          },
        ]}
      />
      {calculatorShow ? (
        <CalculatorPage
          /* 获取数据方法 */
          cloumsData={indicatorData}
          computedFn={setComputedString}
          computedArr={computedData}
          setComputedArr={restModalFormData}
        />
      ) : (
        ''
      )}
    </ModalForm>
  );
};

export default CloumsPage;
